package org.rslai.tcedit.web.testCaseMgt;

import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.hibernate.validator.InvalidStateException;
import org.hibernate.validator.InvalidValue;
import org.rslai.tcedit.domain.Catalog;
import org.rslai.tcedit.exception.ApplicationException;
import org.rslai.tcedit.util.HttpUtil;
import org.rslai.tcedit.util.SessionUtil;
import org.rslai.tcedit.web.core.AbstractMvcController;

/**
 * 测试用例分类
 * 
 * @author rslai
 * 
 * @spring.bean name="/testCaseMgt/catalog.jspx"
 */
public class catalogController extends AbstractMvcController {

	@Override
	public Map<String, Object> getModel(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String method = request.getMethod();
		Map<String, Object> map = new HashMap<String, Object>();
		Catalog catalog = null;

		String action = HttpUtil.getString(request, "action", "").toLowerCase();
		String catalogID = HttpUtil.getString(request, "id", "").toLowerCase();

		try {
			if (method.equals("GET")) {
				// 查询
				catalog = (Catalog) catalogService.query(SessionUtil.getCurrentProductID(request), Catalog.class, catalogID);
			}
		} catch(Exception e) {
			map.put("error", convertException(e));
		}

		map.put("action", action);
		map.put("catalog", catalog);

		return map;
	}

	@Override
	public String getView(HttpServletRequest request, HttpServletResponse response) {
		return "/testCaseMgt/catalog.htm";
	}

	private String convertException(Exception e) throws Exception {
		if (e instanceof ApplicationException) {
			return e.getMessage();
		} else if (e instanceof InvalidStateException) {
			StringBuffer sb = new StringBuffer(128);
			InvalidValue[] ivs = ((InvalidStateException) e).getInvalidValues();
			for (InvalidValue iv : ivs)
				sb.append(iv.getMessage()).append("<br/>");
			return sb.toString();
		}
		throw e;
	}

}
